<?php

namespace App\DB;

use DB;
use App\Exceptions\ReqException;
use Log;

class PermissionDB {
	/**
	 * 获取菜单权限列表
	 *
	 * @param unknown $user        	
	 * @return multitype:|unknown
	 */
	public static function getPermission($user, $type) {
		$sql = 'select distinct p.id, p.`type`, p.`name`, p.url, p.parent_id, p.icon_url, p.icon_css, p.component, p.description, p.is_leaf ';
		$table = 'from sys_users u, sys_user_role ur, sys_role_permission rp, sys_permissions p ';
		$condition = 'where u.uid = ur.uid and ur.role_id = rp.role_id and rp.permission_id = p.id and u.uid = ? and p.type = ?';
		$params = [ 
				$user->uid,
				$type 
		];
		$menu = DB::select ( $sql . $table . $condition, $params );
		if (count ( $menu ) == 0) {
			return [ ];
		}
		
		return $menu;
	}
	
	/**
	 * 获取用户角色
	 *
	 * @param unknown $uid        	
	 * @return multitype:NULL
	 */
	public static function getUserRoles($uid) {
		$sql = 'select uid, role_id from sys_user_role where uid = ?';
		$params = [ 
				$uid 
		];
		$result = DB::select ( $sql, $params );
		
		$roles = [ ];
		foreach ( $result as $item ) {
			$roles [] = $item->role_id;
		}
		return $roles;
	}
	
	/**
	 * 判断用户是否具有某项权限
	 * 
	 * @param unknown $uid        	
	 * @param unknown $type        	
	 * @param unknown $permission        	
	 * @return boolean
	 */
	public static function hasPermission($uid, $type, $permission) {
		$sql = 'select distinct p.id, p.`type`, p.`name`, p.url, p.parent_id, p.icon_url, p.icon_css, p.component, p.description, p.is_leaf ';
		$table = 'from sys_users u, sys_user_role ur, sys_role_permission rp, sys_permissions p ';
		$condition = 'where u.uid = ur.uid and ur.role_id = rp.role_id and rp.permission_id = p.id and u.uid = ? and p.type = ? and p.id = ?';
		$params = [ 
				$user->uid,
				$type,
				$permission 
		];
		$permission = DB::select ( $sql . $table . $condition, $params );
		if (count ( $permission ) > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 生成菜单的树形结构
	 * getMenuTree ( $menu, '0000' )获取菜单树形结构
	 *
	 * @param unknown $menu        	
	 * @param unknown $id        	
	 * @return Ambigous <NULL, unknown>|multitype:Ambigous <unknown, multitype:NULL , NULL>
	 */
	private static function getMenuTree($menu, $id) {
		$item = null;
		if ($id != '0000') {
			$item = self::getMenuItemById ( $menu, $id );
			if (! is_null ( $item->is_leaf ) && $item->is_leaf == '1') {
				return $item;
			}
		}
		$children = [ ];
		foreach ( $menu as $item2 ) {
			if ($item2->parent_id == $id) {
				$children [] = self::getMenuTree ( $menu, $item2->id );
			}
		}
		if ($id == '0000') {
			return $children;
		}
		$item->children = $children;
		return $item;
	}
	private static function getMenuItemById($menu, $id) {
		Log::info ( $id );
		foreach ( $menu as $item ) {
			if ($item->id == $id) {
				return $item;
			}
		}
		return null;
	}
}